package gl.util

import java.io.BufferedInputStream
import java.io.BufferedReader
import java.io.InputStream
import java.net.URL
import java.nio.ByteBuffer
import java.nio.file.Files

object Resource {

    fun getStream(path: String): InputStream? = javaClass.classLoader.getResourceAsStream(path)

    fun getURL(path: String): URL? = javaClass.classLoader.getResource(path)

    fun <R> useStream(path: String, function: (InputStream) -> R) = getStream(path)?.use(function)

    fun <R> useBufferedStream(path: String, function: (BufferedInputStream) -> R) = getStream(path)?.use { it.buffered().use(function) }

    fun <R> useReader(path: String, function: (BufferedReader) -> R) = getStream(path)?.use { it.bufferedReader().use(function) }

    fun getString(path: String) = useReader(path) { it.readText() } ?: ""

    fun getLines(path: String) = useReader(path) { it.readLines() } ?: mutableListOf()

    fun getBytes(path: String) = useStream(path) { it.readAllBytes() } ?: byteArrayOf()

    fun wrapBytes(path: String) = ByteBuffer.wrap(getBytes(path))
}